<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
</head>
<body>
  <div id="app">
    <p v-if="isSuccess">成功了</p>
    <!-- 元素不存在DOM里 -->
    <p v-else>失败了</p>
    <p v-show="isSuccess">成功</p>
    <!-- 通过样式display:none隐藏元素 -->
    <p v-show="!isSuccess">失败</p>
    <button @click="changeState">改变状态</button>

    <ul v-for="(item,index) in arr" :key="index">
      <li>{{item + ' ' + index}}
        <button @click="deleteItem(index)">删除</button>
        <button @click="updateItem(index)">更新</button>
      </li>
    </ul>
    <ul v-for="(value, key) in obj" :key="key">
      <li>{{key + ': ' + value}}</li>
    </ul>
    <input type="text" v-model="searchName">
    <ul v-for="(item, index) in filterPersons" :key="index">
      <li>{{item.name + ': ' + item.age}}</li>
    </ul>
    <button @click=sort(1)>升序</button>
    <button @click=sort(2)>降序</button>
    <button @click=sort(0)>原序</button>
  </div>
  <script src="./vue.js"></script>
  <script>
    const vm = new Vue({
      el: '#app',
      data: {
        isSuccess: true,
        arr: [
          1,2,3,4,5,6
        ],
        obj: {
          'a': 1,
          'b': 2,
          'c': 3
        },
        searchName: '',
        persons: [
          {name: '张三', age: '23'},
          {name: '张三丰', age: '33'},
          {name: '张大强', age: '43'},
          {name: '张国强', age: '53'},
          {name: '李四', age: '13'},
          {name: '李大话', age: '45'},
          {name: '李二分', age: '31'},
          {name: '李通过', age: '22'},
          {name: '王五', age: '24'},
          {name: '王伟', age: '34'},
          {name: '王芳', age: '64'},
          {name: '王器', age: '28'},
        ],
        orderType: 0 //0原序 1升序 2降序
      },
      computed: {
        filterPersons() {
          // 取出相关数据 解构
          const {searchName, persons, orderType} = this
          let fPersons;
          // 对persons过滤
          fPersons = persons.filter(p => p.name.indexOf(searchName) >= 0)
          // 
          if (orderType !== 0) {
            if (orderType === 1) {
              fPersons.sort((p1,p2)=>p1.age-p2.age)
            } else {
              fPersons.sort((p1,p2)=>p2.age-p1.age)
            }
          }
          return fPersons
        }
      },
      methods: {
        changeState() {
          this.isSuccess = !this.isSuccess
        },
        deleteItem(index) {
          // splice直接操作原数组
          this.arr.splice(index, 1) // 删除一个元素
        },
        updateItem(index) {
          // 这样无法修改 没有改变arr本身 只是改变了数组内部的结构
          // vue本身只监视了arr
          // 没有调用vue的变异方法
          // this.arr[index] = 7
          // splice可以实现增删改
          this.arr.splice(index, 1, 7) // 修改一个元素
          // this.arr.splice(index, 0, 7)  // 增加一个元素
        },
        sort(type) {
          this.orderType = type
        }
      }
    })
  </script>
</body>
</html>